#!/bin/bash

echo "=== 多虚拟串口测试脚本 ==="

# 编译模块
echo "1. 编译内核模块..."
make clean && make

if [ $? -ne 0 ]; then
    echo "编译失败！"
    exit 1
fi

# 卸载旧模块
echo "2. 卸载旧模块..."
sudo rmmod vserial_stj 2>/dev/null

# 加载多设备模块
echo "3. 加载4个虚拟串口设备..."
sudo insmod vserial_stj.ko tcp_ip=127.0.0.1 tcp_server_port=5000 num_devices=4

if [ $? -ne 0 ]; then
    echo "加载模块失败！"
    exit 1
fi

# 检查设备文件
echo "4. 检查创建的设备文件..."
ls -la /dev/ttyV*

# 设置权限
echo "5. 设置设备权限..."
sudo chmod 666 /dev/ttyV*

# 启动多个TCP服务器
echo "6. 启动TCP服务器..."
echo "启动端口5000的服务器..."
./tcp_server 5000 &
SERVER1_PID=$!

echo "启动端口5001的服务器..."
./tcp_server 5001 &
SERVER2_PID=$!

echo "启动端口5002的服务器..."
./tcp_server 5002 &
SERVER3_PID=$!

echo "启动端口5003的服务器..."
./tcp_server 5003 &
SERVER4_PID=$!

sleep 2

# 测试各个串口
echo "7. 测试各个虚拟串口..."

echo "测试 /dev/ttyV0 (端口5000)..."
echo "test0" | ./serial_test /dev/ttyV0 &
sleep 1

echo "测试 /dev/ttyV1 (端口5001)..."
echo "test1" | ./serial_test /dev/ttyV1 &
sleep 1

echo "测试 /dev/ttyV2 (端口5002)..."
echo "test2" | ./serial_test /dev/ttyV2 &
sleep 1

echo "测试 /dev/ttyV3 (端口5003)..."
echo "test3" | ./serial_test /dev/ttyV3 &
sleep 1

echo "8. 等待测试完成..."
sleep 5

# 清理
echo "9. 清理进程..."
kill $SERVER1_PID $SERVER2_PID $SERVER3_PID $SERVER4_PID 2>/dev/null

echo "10. 卸载模块..."
sudo rmmod vserial_stj

echo "=== 测试完成 ===" 